<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/10/19 09:44
 */

namespace App\Project\Search;


class Raw
{
    public static function eq($field, $operation, $value)
    {
        return self::normal($field, $operation, $value);
    }

    public static function gt($field, $operation, $value)
    {
        return self::normal($field, $operation, $value);
    }

    public static function lt($field, $operation, $value)
    {
        return self::normal($field, $operation, $value);
    }

    public static function normal($field, $operation, $value)
    {
        $sql = implode(' ', [$field, $operation, '?']);

        return [$sql, $value];
    }

    public static function ex($field)
    {
        if (strpos($field, 'result_b')) {
            return [$field . ' >= 0'];
        }

        return ["({$field} > 0 or {$field} > '')"];
    }

    public static function bt($field, $value)
    {
        sort($value);

        $sql = implode(' ', [$field, 'BETWEEN ?', 'AND', '?']);

        return [$sql, $value];
    }

    public static function in($field, $value)
    {
        $placeholder = array_pad([], count($value), '?');

        $sql = implode(' ', [$field, 'in', '(' . implode(', ', $placeholder) . ')']);

        return [$sql, $value];
    }

    public static function findInSet($field, $values)
    {
        $sql = '';

        foreach ($values as $value) {
            $sql .= " AND FIND_IN_SET(?, {$field})";
        }

        return [ltrim($sql, ' AND '), $values];
    }
}